package com.zhongke.cotrun.service.impl;

import com.zhongke.cotrun.mapper.DictDao;
import com.zhongke.cotrun.model.pojo.DictEntity;
import com.zhongke.cotrun.service.DictService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service("dictService")
public class DictServiceImpl implements DictService {

    @Resource
    DictDao dictDao;

    /**
     * 新增字典
     *
     * @param entity
     * @return
     */
    @Override
    public boolean add(DictEntity entity) {
        try {
            dictDao.add(entity);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 修改字典
     *
     * @param entity
     * @return
     */
    @Override
    public boolean update(DictEntity entity) {
        return dictDao.update(entity);
    }

    @Override
    public List<DictEntity> getAll() {
        return dictDao.selectAll();
    }

    /**
     * 根据类型获取
     *
     * @param type 类型
     * @return
     */
    @Override
    public List<DictEntity> getListByType(String type) {
        return dictDao.getByType(type);
    }

    @Override
    public DictEntity getItemByType(String type) {
        return dictDao.getItemByType(type);
    }

    /**
     * 根据父id获取字典
     *
     * @param parentId
     * @return
     */
    @Override
    public List<DictEntity> getByParentId(Integer parentId) {
        return dictDao.getByParentId(parentId);
    }


    /**
     * 根据id获取
     *
     * @param id
     * @return
     */
    @Override
    public DictEntity getById(Integer id) {
        return dictDao.getById(id);
    }

    @Override
    public DictEntity getByCode(String code) {
        return dictDao.getByCode(code);
    }

    /**
     * 逻辑删除
     *
     * @param id
     * @return
     */
    @Override
    public boolean delById(Integer id) {
        DictEntity entity = new DictEntity();
        if (id != null && id > 0) {
            entity.setId(id);
            entity.setDelFlag(1);
            return dictDao.update(entity);
        } else {
            return false;
        }
    }

    @Override
    @Cacheable(cacheNames = "sysConfig:dict", key = "#type")
    public DictEntity getTreeByType(String type) {
        List<DictEntity> list = dictDao.getByType(type);
        if (!list.isEmpty()) {
            DictEntity entity = list.get(0);
            getTreeByParentId(entity);
            return entity;
        } else {
            return null;
        }
    }

    @Override
    public String selectValueInCodes(String codes) {
        return dictDao.selectValueInCodes(codes);
    }

    public void getTreeByParentId(DictEntity entity) {
        List<DictEntity> list = dictDao.getByParentId(entity.getId());
        entity.setChildren(list);
        if (!list.isEmpty()) {
            for (DictEntity d : list) {
                getTreeByParentId(d);
            }
        }
    }
}
